<?php
    include_once("../action/checkAuthenticationAction.php");
    include_once("../service/productService.php");
    include_once("../service/categoryService.php");
    include_once("../util/constant.php");
    include_once("../util/message.php");
	include_once("../util/functionUtil.php");
	include_once("../util/authUtil.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Chi tiết sản phẩm</title>
	<?php 
        include("import-css.php");
        include("import-css-upload.php");
    ?>
    <style>
    ul { list-style-type: none; }
    ul#attribute li { background-color: #E0E0E0; cursor: s-resize; margin: 3px; }
    table td { vertical-align: top; }
    </style>
</head>
<body>
    <?php include("header.php");?>
    
	<div class="container-fluid">
		<div class="row-fluid">
            <?php include_once("menu.php");?>
			<div id="content" class="span10">
            	<?php
					$class = null;
					$message = null;
					
					if(isset($_GET["action"])){
						$action = $_GET["action"];
						
						if($action == INSERT_FAILED){
							$message = $messages["createProductFailed"];
							$class = FAILED_MESSAGE_CLASS;
						} else if($action == INSERT_SUCCESSFULLY){
							$message = $messages["createProductSuccessfully"];
							$class = SUCCESSFULL_MESSAGE_CLASS;
						} else if($action == INSERT_FAILED.".1"){
							$message = $messages["createProductAttributeFailed"];
							$class = FAILED_MESSAGE_CLASS;
						} else if($action == INSERT_FAILED.".2"){
							$message = $messages["createProductOptionalPriceFailed"];
							$class = FAILED_MESSAGE_CLASS;
						} else if($action == INSERT_FAILED.".3"){
							$message = $messages["createProductImageFailed"];
							$class = FAILED_MESSAGE_CLASS;
						} else if($action == UPDATE_SUCCESSFULLY){
							$message = $messages["editProductSuccessfully"];
							$class = SUCCESSFULL_MESSAGE_CLASS;
						}
							
						if(isset($class)){
				?>
							<div id="msg" class="center alert <?php echo($class);?>"><?php echo($message);?></div>
				<?php		
						}
					}
				?>                
                <div class="box">
                    <div class="box-content">
                    	<?php
							if(!authUtil(array("edit product","create product","view product"),$perm_array,false)){
								echo "<script>window.location.href='../admin/index.php';</script>";
							}
						?>
                        <form id="fileupload" action="" method="post" enctype="multipart/form-data" onsubmit="validateCurrency('price');validateCurrency('\'optionalPrices[]\'');" class="form-horizontal">
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Loại sản phẩm</label>
                                <div class="controls">
                                    <?php                          
                                        $proId = 0;// for new action
                                        unset($_SESSION["proId"]);
                                        $_SESSION["uploadMode"] = UPLOAD_MODE_PRODUCT;
                                        $_SESSION["newAction"] = "1";
										
                                        if(isset($_GET["id"])){
                                            $proId = $_GET["id"];    	
                                            $_SESSION["proId"] = $proId; // for upload images
                                            unset($_SESSION["newAction"]);
                                            $productInfo = findProductBy($proId);
                                        }
                                        
                                        $categories = getTreeOfCategories(0);
                                        $firstCatId = 0;
                                        $count = 0;
                                    ?>
                                    <select name="category" class="selectpicker" onchange="getAttributes(this.value);getOptionalItems(this.value);removeLabel();" <?php if($proId != 0) echo "disabled";?>>
                                        <?php
                                            foreach($categories as $row){
                                                if($proId == 0){
                                                    if($count == 0) $firstCatId = $row["id"];
                                                }
                                                
                                                if($row["id"] == $productInfo["CAT_ID"]){
                                                    $firstCatId = $row["id"];
                                        ?>
                                                    <option value="<?php echo $row["id"];?>" selected><?php echo $row["name"];?></option>
                                        <?php
                                        
                                                } else {
                                        ?>
                                                <option value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option>
                                        <?php
                                                }
                                                $count++;
                                            }
                                        ?>
                                     </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Khuyến mãi</label>
                                <div class="controls">
                                    <select data-rel="chosen" name="discount">
                                        <option value="">Không</option>
                                        <?php
                                            $discounts = getAllDiscounts();
                                            while($row = ConnectionManager::getInstance()->fetch($discounts)){
                                                if($productInfo["DIS_ID"] == $row["DIS_ID"]){
                                        ?>
    									            <option value="<?php echo $row["DIS_ID"];?>" selected><?php echo $row["DIS_NAME"];?></option>
                                                <?php
                                                } else {
                                                ?>
                                                    <option value="<?php echo $row["DIS_ID"];?>"><?php echo $row["DIS_NAME"];?></option>
                                                <?php
                                                }                                                            
                                                ?>
                                        <?php
                                            }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Sản phẩm</label>
                                <div class="controls">
                                    <input type="text" name="name" class="input-xlarge focused" value="<?php if($proId != 0) echo $productInfo["PRO_NAME"];?>">
                                </div>
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Mã</label>
                                <div class="controls">
                                    <input type="text" name="code" id="code" maxlength="10" class="input-xlarge focused" value="<?php if($proId != 0) echo $productInfo["PRO_CODE"];?>">
                                    <input type="hidden" id="hiddenCode" maxlength="10" class="input-xlarge focused" value="<?php if($proId != 0) echo $productInfo["PRO_CODE"];?>">
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label" for="selectError">Hiện/Ẩn</label>
                                <div class="controls">
                                     <select class="selectpicker" name="visibility">
                                        <?php
                                            $statuses = array(1 => "Hiện", 
                                                              2 => "Ẩn");
                                            while($status = current($statuses)){
                                                if(key($statuses) == $productInfo["PRO_STATUS"]){
                                        ?>
                                                    <option value="<?php echo key($statuses); ?>" selected><?php echo($status);?></option>
                                        <?php
                                                } else {
                                        ?>
                                                    <option value="<?php echo key($statuses); ?>"><?php echo($status);?></option>
                                        <?php            
                                                    
                                                }
                                                next($statuses);
                                            }
                                        ?>
                                     </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label" for="selectError">Trạng thái</label>
                                <div class="controls">
                                    <select class="selectpicker" name="status">
                                        <?php
                                            $statuses = findAllProductStatuses();
                                            while($row = mysql_fetch_array($statuses)){
                                                if($productInfo["PRO_STAT_ID"] == $row["PRO_STAT_ID"]){
                                        ?>
                                                <option value="<?php echo $row["PRO_STAT_ID"];?>" selected><?php echo $row["PRO_STAT_NAME"];?></option>
                                        <?php
                                                } else{
                                        ?>
                                                <option value="<?php echo $row["PRO_STAT_ID"];?>"><?php echo $row["PRO_STAT_NAME"];?></option>
                                        <?php    
                                                }
                                            } 
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="control-group">
                                <label for="categoryTitle" class="control-label">Giá</label>
                                <div class="controls">
                                    <input type="text" name="price" class="input-xlarge focused" onkeyup="this.value = formatCurrency(this.value,2);" value="<?php if($proId != 0) echo  number_format($productInfo["PRO_PRICE"], 0, ".", ",");?>"/>
                                </div>
                            </div>
                            <div class="control-group">
                                <label class="control-label" for="textarea2">Mô tả</label>
                                <div class="controls">
                                    <textarea class="ckeditor" id="textarea2" rows="3" name="description"><?php if($proId != 0) echo $productInfo["PRO_DESCRIPTION"];?></textarea>
                                </div>
    						</div>
                            <table>
                                <tr>
                                    <td>
                                        <div class="control-group">
                                            <label class="control-label" for="textarea2">Thuộc tính</label>
                                            <div class="controls">
                                                <ul id="attribute" name="attribute" class="sortable-attribue">
                                                    <?php
                                                        $categoryList = getAllParentCategoriesOf($firstCatId, null);
                                                        $categoryList[] = array("id" => $firstCatId);
                                                        $attributeValues = array();
                                                        
                                                        foreach($categoryList as $each){
                                                            $attributes = getAttributesOfCategory($each["id"]);
																
                                                            while($row = ConnectionManager::getInstance()->fetch($attributes)){
																if($proId != 0){
																	$attributeValue = findAttributeValueBy($each["id"], $row["ATT_ID"], $proId);
																	$attributeValues[] = array("id" => $row["ATT_ID"], "name" => $row["ATT_NAME"],"value" => $attributeValue["AVAL_VALUE"], "order" => $attributeValue["AVAL_ORDER"]);
																} else { 
													?>
                                                    				<li>
                                                                        <div><?php echo $row["ATT_NAME"];?>:</div>
                                                                        <input type="text" name="attributes[<?php echo $row["ATT_ID"];?>]" value=""/>
                                                                        <input type='hidden' name='attIds[]' value="<?php echo $row["ATT_ID"];?>"/>
                                                                    </li> 
                                                    <?php
																}
															}
														}
														
														if($proId != 0){	
															$orderedAttributeValues = sortByKeyValue($attributeValues, "order", SORT_ASC);
															foreach($orderedAttributeValues as $each){$count++;
                                                    ?>
                                                                <li>
                                                                    <div><?php echo $each["name"]?>:</div>
                                                                    <input type="text" name="attributes[<?php echo $each["id"];?>]" value="<?php echo $each["value"];?>"/>
                                                                    <input type='hidden' name='attIds[]' value="<?php echo $each["id"];?>"/>
                                                                </li> 
                                                    <?php
															}
														}
                                                    ?>
                                                </ul>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="control-group">
                                            <label class="control-label" for="textarea2">Lựa chọn</label>
                                            <div class="controls">
                                                <ul id="optionalPrice" name="optionalPrice" class="sortable-optional-price">
                                                    <?php
                                                        foreach($categoryList as $each){
                                                            $optionalPrices = getOptionalPricesOfCategory($each["id"]);
                                                            while($row = ConnectionManager::getInstance()->fetch($optionalPrices)){
                                                                if($proId != 0) $optionalPrice = findOptionalPriceBy($each["id"], $row["OPP_ID"], $proId);
                                                    ?>
                                                                <li>
                                                                    <div><?php echo $row["OPP_NAME"];?>:</div>
                                                                    <?php
                                                                        $optionalItems = findOptionItemByOptionalPrice($row["OPP_ID"]);
                                                                        while($item = ConnectionManager::getInstance()->fetch($optionalItems)){
                                                                            echo "&nbsp- ".$item["OOI_NAME"]."<br/>";
                                                                        }
                                                                        /*<input type="text" name="optionalPrices[<?php echo $row["OPP_ID"];?>]" onkeyup="this.value = formatCurrency(this.value,2);" value="<?php echo $optionalPrice["OPV_VALUE"] != "" ? number_format($optionalPrice["OPV_VALUE"], 0, ".", ","): "";?>"/>
                                                                        <input type="hidden" name="oppIds[]" value="<?php echo $row["OPP_ID"];?>"/>*/
                                                                    ?>
                                                                </li>
                                                    <?php
                                                            }
                                                        }
                                                    ?>
                                                </ul>
                                            </div>
                						</div>
                                    </td>
                                </tr>
                            </table>
                            <?php
                                if(isset($proId) && $proId > 0){
                            ?>
                            <div class="control-group">
                                <label class="control-label" for="textarea2">Hình ảnh</label>
                                <div class="controls">
                                    <div class="row fileupload-buttonbar" style="margin: 3px;">
                                        <div class="col-lg-7">
                                            <!-- The fileinput-button span is used to style the file input field as button -->
                                            <span class="btn btn-success fileinput-button">
                                                <i class="glyphicon glyphicon-plus"></i>
                                                <span>Thêm hình</span>
                                                <input type="file" name="files[]" multiple>
                                            </span>
                                            <?php
												$require_perm = array("edit product");
												if(authUtil($require_perm,$perm_array,true)){
                                        	?>
                                            <button type="submit" class="btn btn-primary start">
                                                <i class="glyphicon glyphicon-upload"></i>
                                                <span>Tải hình</span>
                                            </button>
                                            <?php
												}
                                            ?>
                                            <button type="button" class="btn btn-danger delete" onclick="deleteImage('');">
                                                <i class="glyphicon glyphicon-trash"></i>
                                                <span>Xóa</span>
                                            </button>
                                            <input type="checkbox" class="toggle">
                                            <!-- The loading indicator is shown during file processing -->
                                            <span class="fileupload-loading"></span>
                                        </div>
                                        <!-- The global progress information -->
                                        <div class="col-lg-5 fileupload-progress fade">
                                            <!-- The global progress bar -->
                                            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                                                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                                            </div>
                                            <!-- The extended global progress information -->
                                            <div class="progress-extended">&nbsp;</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php
                                }
                            ?>
                            <!-- The table listing the files available for upload/download -->
                            <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
                            <div class="form-actions">
                                <?php
                                    if(!isset($_GET["id"])){
                                ?>
                                		<?php
											$require_perm = array("create product");
											if(authUtil($require_perm,$perm_array,true)){
                                        ?>
	                                        <button type="button" class="btn btn-primary" onclick="customValidate();generateImageNames('imgPaths');submitForm('fileupload', '../action/newProductAction.php', 'post');">Tạo mới</button>
                                        <?php
											}
                                        ?>
                                <?php
                                    } else {
                                ?>  
                                        <?php
											$require_perm = array("edit product");
											if(authUtil($require_perm,$perm_array,true)){
                                        ?>
	                                        <button type="button" class="btn btn-primary" onclick="customValidate();submitForm('fileupload', '../action/editProductAction.php', 'post');">Chỉnh sửa</button>    
                                        <?php
											}
                                        ?>
                                <?php
                                    }
                                ?>
    						</div>
                            <input type="hidden" value="" id="imgPaths" name="imgPaths"/>
                            <input type="hidden" value="<?php echo $_GET["id"];?>" id="proId" name="proId"/>
                            <div id="tmpData">
                            <?php
                                //put all ids and names of product image to hidden fields
                                //$imageList = findImagesOfProduct($proId);
                                
                                //while($row = ConnectionManager::getInstance()->fetch($imageList)){
                            ?>
                                    <!--<input type="text" name="data" value="<?php echo $row["IMG_ID"].",".$row["IMG_PATH"];?>">-->
                            <?php    
                                //}
                            ?>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div><!-- end of row-fluid -->
        <?php include("footer.php");?>
    </div><!-- container-fluid -->
    
    <!-- The template to display files available for upload -->
    <script id="template-upload" type="text/x-tmpl">
	{% for (var i=0, file; file=o.files[i]; i++) { %}
		<tr class="template-upload fade">
			<td>
				<span class="preview"></span>
			</td>
			<td>
				<p class="name">{%=file.name%}</p>
				{% if (file.error) { %}
					<div><span class="label label-danger">Lỗi</span> {%=file.error%}</div>
				{% } %}
			</td>
			<td>
				<p class="size">{%=o.formatFileSize(file.size)%}</p>
				{% if (!o.files.error) { %}
					<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
				{% } %}
			</td>
			
			<td>
				{% if (!o.files.error && !i && !o.options.autoUpload) { %}
					<button class="btn btn-primary start" style="visibility: hidden;">
						<i class="glyphicon glyphicon-upload"></i>
						<span>Bắt đầu</span>
					</button>
				{% } %}
				{% if (!i) { %}
					<button class="btn btn-warning cancel">
						<i class="glyphicon glyphicon-ban-circle"></i>
						<span>Hủy</span>
					</button>
				{% } %}
			</td>
		</tr>
	{% } %}
	</script>
	<!-- The template to display files available for download -->
	<script id="template-download" type="text/x-tmpl">
	{% for (var i=0, file; file=o.files[i]; i++) { %}
		<tr class="template-download fade">
			<td>
				<span class="preview">
					{% if (file.url) { %}
					       <a href="{%=file.thumbnailUrl%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
					{% } %}
				</span>
			</td>
			<td>
				<p class="name">
					{% if (file.url) { %}
						<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.url?'data-gallery':''%}>{%=file.name%}</a>
					{% } else { %}
						<span>{%=file.name%}</span>
					{% } %}
				</p>
				{% if (file.error) { %}
					<div><span class="label label-danger">Lỗi</span> {%=file.error%}</div>
				{% } %}
			</td>
			<td>
				<span class="size">{%=o.formatFileSize(file.size)%}</span>
			</td>
			<td>
				<p class="name">
					{% if (file.url) { %}
							<span onclick="$(this).selectText();">{%=file.url%}</span>
					{% } %}
				</p>
			</td>
			<td>
				{% if (file.deleteUrl) { %}
					<button onclick="deleteImage('{%=file.name%}');" class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
						<i class="glyphicon glyphicon-trash"></i>
						<span>Xóa</span>
					</button>
					<input type="checkbox" name="delete" value="{%=file.name%}" class="toggle">
				{% } else { %}
					<button class="btn btn-warning cancel">
						<i class="glyphicon glyphicon-ban-circle"></i>
						<span>Hủy</span>
					</button>
				{% } %}
			</td>
		</tr>
	{% } %}
	</script>
    <?php include("import-js.php");?>
    <?php include("import-js-upload.php");?>
    <script>
        var isValid = true;
        $(document).ready(function() {
            $("#attribute").sortable({connectWith: "sortable-attribue"});
			
            $.validator.addMethod("checkUniqueCode", function(value, element) {
                 
                if($("#code").val() == ""){
                    $.validator.messages.checkUniqueCode = "<?php echo $messages["validation.required"];?>";
                    return false;  
                } else{
                    if($("#code").val() == $("#hiddenCode").val()) isValid = true;
                    else{
                        $.ajax({
                            type: "POST",
                            url: "../action/ajax/checkUniqueProductCodeProcess.php",
                            data: {"code" : $("#code").val()},
                            success: function(data){
                                if(data == 1) {
									isValid = true;   
								}
                                else {
                                    $.validator.messages.checkUniqueCode = "<?php echo $messages["validation.existedProductCode"];?>";
                                    isValid = false;   
                                }   
                            }
                        });
                    }
                }
                return isValid;
            }, $.validator.messages.checkUniqueCode);
            
			
			
            $("#fileupload").validate({
                rules: {
                    name: { required: true },
                    price: { required: true },
                    code: { checkUniqueCode: true },
                    status: { required: true }
                },
                
                messages: {
                    name: "<?php echo $messages["validation.required"];?>",
                    price: "<?php echo $messages["validation.required"];?>",
                    status: "<?php echo $messages["validation.required"];?>"
                }
            });
			
			customValidate();
        });
        
		function customValidate(){
			$("[name^=attributes]").each(function(){
				$(this).rules("add",{
					required: true,
					messages:{
						required: "<?php echo $messages["validation.required"];?>"
					}
				});
			});
			
			$("[name^=optionalPrices]").each(function(){
				$(this).rules("add",{
					required: true,
					messages:{
						required: "<?php echo $messages["validation.required"];?>"
					}
				});
			});
		}
		
        function getAttributes(catId){
            $.ajax({  
                type: "POST",  
                url: "../action/ajax/getAttributesOfCategoryProcess.php",  
                data: "catId=" + catId,
                async: false,  
                success: function(data) {  
                    $("#attribute").children().remove();
                    $("#attribute").append(data);
                }
            });
        }
        
        function getOptionalItems(catId){
            $.ajax({  
                type: "POST",  
                url: "../action/ajax/getOptionalItemsOfCategoryProcess.php",  
                data: "catId=" + catId,
                async: false,  
                success: function(data) {
                    $("#optionalPrice").children().remove();
                    $("#optionalPrice").append(data);
                }
            });
        }
        
        function removeLabel(){
            $("label.error").empty();
        }
        
        // insert images into databaes
        function storeImage(){
            if($("#proId").val() != ""){
                var dataString = "imgPaths=" + $("#imgPaths").val() + "&id=" + $("#proId").val();
                $.ajax({
                    type: "POST",
                    url: "../action/ajax/storeProductImageProcess.php",
                    data: dataString,
                    success: function(data){
                        console.log(data);
                    }
                });
            }
        }
        
        function deleteImage(name){
            var names = new Array();
            
            $('input[name^=delete]').each(function() {
                if($(this).is(':checked')) names.push($(this).val());
            });
            
            var dataString = "name=" + name + "&names=" + names + "&proId=" + $("#proId").val();
            
            $.ajax({
                type: "POST",
                url: "../action/ajax/deleteProductImageProcess.php",
                data: dataString,
                success: function(data){
                    $("#imgPaths").val("");
                }
            });
        }
        
        function generateImageIds(){
            var data = new Array();
            
            $('input[name^=data]').each(function() {
                data.push($(this).val());
            });
            
            $('input[name^=imgIds]').each(function() {
                for(var i = 0; i < data.length; i++){
                    var tmp = data[i].split(",");
                    if(tmp[1] == $(this).val()){
                        $(this).val(tmp[0]);
                    }
                }
            });
        }
		
		// Initialize the jQuery File Upload widget:
		$('#fileupload').fileupload({
			url: '../image/',
			maxFileSize: <?php echo MAX_FILE_SIZE;?>,
			acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
		}).bind('fileuploadalways', function (e, data) {
		    var fileNames = extractFileNameFromFullPath(data.result.files);
            if(fileNames != ""){
                $("#imgPaths").val(fileNames);
	            storeImage();
            }  
		});
    </script>
</body>
</html>